// pages/mime/mime.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    permission: false,
    userInfo: null,
    hasLogin: false,
    site: null,
    popshow: false,//弹窗
    canvasShow: true,
    currentLibrary: null,
    libraryList: [],//图书馆列表
    per: 0,
    screenWidth: 750, //实际设备的宽度
    draw: 'circwewle1',
    r: '85',
    size: 0, //画板大小
    step: 1, //用来算圆的弧度0-2
    txt: 0,
    myPeriods: 0,
    sign_count: 0,
  },
  myAudioTours: function () {
    console.log('查看我的语音讲解')
    wx.navigateTo({
      url: "/pages/mime/myAudioTours/myAudioTours"
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.setBackgroundColor({
    //   backgroundColor: '#000', // 窗口的背景色为白色
    // })
    this.setData({
      site: app.globalData.site
    })
  },

  //单位切换
  showPop:function(){
    this.setData({
      popshow:true,
      canvasShow:false
    })
    this.getLibraryList()
    console.log(this.data.currentLibrary)
  },

  getLibraryList:function(){
    var _site = app.globalData.site
    var encarr = [{
      phone: wx.getStorageSync('phone')
    }, {
      fid: _site.fid
    }, {
      libraryType: 3
    }]
    var enc = app.generateEnc(encarr)
    wx.request({
      url: 'https://manageshequ3.chaoxing.com/api/getsitesbyuid',
      data:{
        fid: _site.fid,
        phone: wx.getStorageSync('phone'),
        libraryType: 3, //类型 1图书馆 add by carlos at 2020-05-20
        sid: 1 ,//预留字段 add by carlos at 2020-05-20
        enc:enc
      },
      success:(res)=>{
        console.log(res.data.data)
        // let site = {
        //   fid: 117890,
        //   id: 1,
        //   fidEnc: 'd6517f679046dcf3',
        //   name: '超星读书',
        //   custom: '{audio:{"id": 1,"key":"rtertertert"}}'
        // }
        // res.data.data.push(site)
        var records = res.data.data
        records.forEach(t => {
          try {
            JSON.parse(t.custom)
        } catch (error) {
            t.custom = t.custom != '' ? app.decrypt(t.custom) : t.custom
            t.appid = t.appid != '' ? app.decrypt(t.appid) : t.appid
            t.fidEnc = t.fidEnc != '' ? app.decrypt(t.fidEnc) : t.fidEnc
            t.fidEncH5 = t.fidEncH5 != '' ? app.decrypt(t.fidEncH5) : t.fidEncH5
            t.secret = t.secret != '' ? app.decrypt(t.secret) : t.secret
        }
        })
        this.setData({
          libraryList: records
        })
      }
    })
  },

  //选择图书馆
  checkCurrentLibrary: function (e) {    
    var currentId = e.currentTarget.dataset.id;    
    this.data.libraryList.forEach((item, idx) => {
      if (item.id === currentId) {
        this.setData({
          currentLibrary: this.data.libraryList[idx]
        })
      }
    })
  },

  //图书馆确定按钮
  bindsure: function () {    
    console.log(this.data.currentLibrary);
    var site = this.data.currentLibrary
    wx.setStorageSync('site', site);
    wx.setStorageSync('fid', site.fid);
    app.globalData.fid = site.fid;
    app.globalData.fidEnc = site.fidEnc;
    app.globalData.province = site.province;
    app.globalData.city = site.city;
    app.globalData.district = site.district;
    app.globalData.allowLocation = true;
    app.globalData.site = site;
    if (site.data) { //如果有小组id
      app.globalData.bbsid = site.data.communityId
      app.globalData.bbsidMsg = site.data
    } else {
      app.globalData.bbsid = ''
      app.globalData.circleId = ''
      app.globalData.bbsidMsg = {}
    }
    this.setData({
      site: app.globalData.site,
      canvasShow: true,
      popshow: false,
      libraryList: [],
      currentLibrary: null
    })
    this.getPeriod();
    // this.getReadBookTimes();
    this.getPunchCardSum();
    this.getjrljscore();
    this.initcircleprogess();
    wx.reLaunch({
      url: '/pages/mime/mime'
    })
  },

  //获取用户积分
  getPeriod: function () {
    var encarr = [{
      fid: app.globalData.fid
    }, {
      uid: wx.getStorageSync('cxid')
    }, {
      wxType: app.globalData.wxTypes[7].id
    }]
    var enc = app.generateEnc(encarr)
    var that = this;
    wx.request({
      url: app.url.scoreshequ3BaseUrl+'services/ScoreService/getScore',
      data: {
        fid: app.globalData.fid,
        uid: wx.getStorageSync('cxid'),
        wxType: app.globalData.wxTypes[7].id,
        enc: enc
      },
      success: function(res) {
        if (res.data.result == "0" && res.data.obj != undefined) {
          that.setData({
            myPeriods: res.data.obj.score + res.data.obj.score_used
          })
        } else {
          console.log("积分为0");
        }
      },
      fail: function() {
        console.log("获取积分异常");
      }
    })
  },

  getPunchCardSum: function() {
    var encarr = [{
        fid: app.globalData.fid
      }, {
        uid: wx.getStorageSync('cxid')
      }, {
        wxType: app.globalData.wxTypes[7].id
      }]
      var enc = app.generateEnc(encarr)
      wx.request({
        url: app.url.scoreshequ3BaseUrl+'services/SignService/getSignInfo',
        data: {
          fid: app.globalData.fid,
          uid: wx.getStorageSync('cxid'),
          wxType: app.globalData.wxTypes[7].id,
          enc: enc
        },
      success: (res) => {
        if(res.data.result == "1"){
          this.setData({
            sign_count: '0'
          })
        }else{
          this.setData({
            sign_count: res.data.obj.sign_count
          })
          let lastSignTime = res.data.obj.lastSignTime;
          let yesterday = new Date(new Date - 1000 * 60 * 60 * 24).Format("yyyy-MM-dd")
          let currentDate = (new Date()).Format(("yyyy-MM-dd"))
          let lastDate = (new Date(lastSignTime)).Format(("yyyy-MM-dd"))
          if (currentDate === lastDate) {
            this.setData({
              ifpunchcard: true
            })
          } else {
            this.setData({
              ifpunchcard: false
            })
            if (lastDate != yesterday) {
              this.setData({
                sign_count: 0,
                // signcountArr:[]
              })
            }
          }
        }
      }
    })
  },

  getjrljscore: function() {
    var encarr = [{
        fid: app.globalData.fid
      }, {
        uid: wx.getStorageSync('cxid')
      }, {
        wxType: app.globalData.wxTypes[7].id
      }]
      var enc = app.generateEnc(encarr)
      wx.request({
        url: app.url.scoreshequ3BaseUrl+'services/ScoreService/getTodayScore',
        data: {
          fid: app.globalData.fid,
          uid: wx.getStorageSync('cxid'),
          wxType: app.globalData.wxTypes[7].id,
          enc: enc
        },
      success: (res) => {
        this.setData({
          per:res.data.obj
        })
        this.initcircleprogess();
      }
    })
  },

  initcircleprogess() {
    var _this = this
    //获取屏幕宽度
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          screenWidth: res.windowWidth
        });
      },
    });
    //初始化
    const el = _this.data.draw; //画板元素
    const r = Number(_this.data.r); //圆形半径
    //获取屏幕宽度(并把真正的半径px转成rpx)
    let rpx = (_this.data.screenWidth / 750) * r;
    //计算出画板大小
    _this.setData({
      size: rpx * 2
    });
    const w = 4; //圆形的宽度
    const per = this.data.per; //圆形进度
    _this.setData({
      step: (2 * Number(_this.data.per)) / 100,
      txt: _this.data.per
    });
    _this.drawCircleBg(el + 'bg', rpx, w); //绘制 背景圆环
    _this.drawCircle(el, rpx, w, _this.data.step); //绘制 彩色圆环
  },

  //圆环进度条
  drawCircleBg: function(el, r, w) {
    const ctx = wx.createCanvasContext(el, this);
    ctx.setLineWidth(w); // 设置圆环的宽度
    ctx.setStrokeStyle('#E5E5E5'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(r, r, r - w, 0, 2 * Math.PI, false);
    //设置一个原点(110,110)，半径为100的圆的路径到当前路径
    ctx.stroke(); //对当前路径进行描边
    ctx.draw();
  },

  /**
   * el:画圆的元素
   * r:圆的半径
   * w:圆的宽度
   * step:圆的弧度 (0-2)
   * 功能:彩色圆环
   */
  drawCircle: function(el, r, w, step) {
    var context = wx.createCanvasContext(el, this);
    // 设置渐变
    var gradient = context.createLinearGradient(2 * r, r, 0);
    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");
    context.setLineWidth(w);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath(); //开始一个新的路径
    // step 从0到2为一周
    context.arc(r, r, r - w, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
    context.stroke(); //对当前路径进行描边
    context.draw()
  },

  //关闭弹窗
  closeWrapper: function () {
    this.setData({
      popshow: false,
      libraryList: [],
      currentLibrary:null,
      canvasShow:true
    })
    this.getjrljscore();
    this.initcircleprogess();
    this.getPeriod();
  },

  toyydlHandle: function () {
    console.log("-----------")
    console.log(wx.getStorageSync('token'))
    // /pages/yyindex/yyindex;
    var phoneNumber = wx.getStorageSync('token')
    if (phoneNumber !== '') {
      wx.navigateTo({
        url: '/pages/yyindex/yyindex',
      })
    } else {
      
      this.selectComponent('#vanpopup').getpopupstate()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    //登录
    var hasLogin = wx.getStorageSync('hasLogin');
    var permission = wx.getStorageSync('permission');
    this.setData({
      hasLogin: hasLogin == undefined ? false : hasLogin,
      permission: permission == undefined ? false : permission
    })
   
    let cxid = wx.getStorageSync('cxid');
    var user = wx.getStorageSync('userInfo');
    if (user != null && user != undefined && user != "") {
      this.setData({
        userInfo: user
      })
    }
    if (!cxid) {//登录过期，重新获取cookieKey
      wx.login({
        success: res => {
          if (res.errMsg == 'login:ok') {
            wx.setStorageSync('code', res.code);
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 登录
   */
  toLogin: function(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  }
})